package com.example.gobang.utils;

import com.example.gobang.constant.Constants;
import com.example.gobang.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;
@Slf4j
public class JWTUtils {

    private static final String secret = "0QFsDcK5qJOizkKUA15AuKTaK68mQgNv8Fo+poT2W9I=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    private static final long JWT_EXPIRATION = 60 * 60 * 1000;
    // 使用 JWT 生成token
    public static String generateToken(Map<String, Object> secret){
        return Jwts.builder().setClaims(secret)
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
                .signWith(key).compact();
    }

    // 验证token
    public static Claims verityToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        } catch (Exception e){
            log.error("解析token失败....");
            return claims;
        }
        return claims;
    }

    // 根据token获取userInfo
    public static User getUserIdByToken(String token){
        Claims claims = verityToken(token);
        User userInfo = null;
        if(claims != null){
            userInfo = (User) claims.get(Constants.TOKEN_USERINFO);
            if(userInfo != null){
                return userInfo;
            }
        }
        return userInfo;
    }

    // 根据token 获取 userName
    public static String getUserNameByToken(String token){
        Claims claims = verityToken(token);
        String userName = null;
        if(claims != null){
            userName = (String) claims.get(Constants.TOKEN_USERNAME);
        }
        return userName;
    }
}
